package com.linkage.jz.bankruptcy.fragment.Vote;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Vote.ProVoteEditVoteActivity;
import com.linkage.jz.bankruptcy.activity.Vote.ProVoteEditVoteNewActivity;
import com.linkage.jz.bankruptcy.activity.Vote.ProVoteMyGroupsActivity;
import com.linkage.jz.bankruptcy.bean.Vote.ProVote;
import com.linkage.jz.bankruptcy.bean.Vote.ProVoteMyVote;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.BundleUtils;
import com.linkage.jz.bankruptcy.utils.LogUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.seapeak.recyclebundle.BaseHolder;
import com.seapeak.recyclebundle.BaseRecyclerAdapter;

import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 债权人表决详情页Tab之表决进度
 */
public class ProVoteDetailMyVoteFragment extends ProVoteBaseFragment implements View.OnClickListener {

    public static final String ARG_PARAM = "arg_param";
    private ProVote proVote;
    private View rootView;
    Fragment fragment;
    private boolean allowChange;

    private LRecyclerView mRecyclerView;
    private LRecyclerViewAdapter mAdapter;
    private VoteGroupAdapter mDataAdapter;
    private List<ProVoteMyVote> list;

    private LinearLayout layoutVoteInfo;
    private TextView myVoteResult;
    private TextView myVoteOpinion;
    private TextView textAllowChange;
    private Button btnAllowChange;

    private LinearLayout layoutVoteEmpty;
    private TextView textVoteEmpty;
    private LinearLayout layoutVoteGoVote;
    private Button gotoVote;

    public static ProVoteDetailMyVoteFragment newInstance() {
        ProVoteDetailMyVoteFragment fragment = new ProVoteDetailMyVoteFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        proVote = BundleUtils.getProVote();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(null == rootView) {
            rootView = inflater.inflate(R.layout.fragment_pro_vote_detail_my_vote, container, false);
        }
        mRecyclerView = rootView.findViewById(R.id.list);
        list = new ArrayList<>();
        mDataAdapter = new VoteGroupAdapter(list);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setRefreshProgressStyle(ProgressStyle.LineSpinFadeLoader); //设置下拉刷新Progress的样式
        mRecyclerView.setArrowImageView(com.github.jdsjlzx.R.drawable.progressbar);  //设置下拉刷新箭头
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);

        mAdapter = new LRecyclerViewAdapter(mDataAdapter);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                ProVoteMyVote item = list.get(position);
//                Intent intent = new Intent(getActivity(), ProVoteEditVoteActivity.class);
//                intent.putExtra("vote", item.isVote());
//                intent.putExtra("voteId", item.getVoteId());
//                intent.putExtra("groupId", item.getGroupId());
//                intent.putExtra("allowChange", item.isAllowChange());
//                if(item.isVote()) {
//                    intent.putExtra("voteOpinion", item.getVoteOpinion());
//                    intent.putExtra("supplementOpinion", item.getSupplementOpinion());
//                }
//                getActivity().startActivityForResult(intent, ProVoteEditVoteActivity.REQUEST_CODE_VOTE);
                ProVoteEditVoteNewActivity.start(getActivity(),list,item);

            }
        });

        mRecyclerView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                fetchMyVote();
            }
        });
        mRecyclerView.setPullRefreshEnabled(true);
        mRecyclerView.setLoadMoreEnabled(false);

        layoutVoteInfo = rootView.findViewById(R.id.layout_vote_info);
        myVoteResult = rootView.findViewById(R.id.my_vote_result);
        myVoteOpinion = rootView.findViewById(R.id.my_vote_desc);
        textAllowChange = rootView.findViewById(R.id.txt_operate_change);
        btnAllowChange = rootView.findViewById(R.id.btn_operate_change);
        layoutVoteEmpty = rootView.findViewById(R.id.layout_vote_empty);
        layoutVoteGoVote = rootView.findViewById(R.id.layout_vote_go_vote);
        gotoVote = rootView.findViewById(R.id.btn_go_vote);


        if("1".equalsIgnoreCase(proVote.getAuth().getDoVote())||"true".equalsIgnoreCase(proVote.getAuth().getDoVote())) {

        }
        gotoVote.setOnClickListener(this);
        if(proVote.getStatus() <= 1) {
            mRecyclerView.setVisibility(View.GONE);
            layoutVoteInfo.setVisibility(View.GONE);
            layoutVoteGoVote.setVisibility(View.GONE);
            layoutVoteEmpty.setVisibility(View.VISIBLE);
        }else {
            mRecyclerView.forceToRefresh();
        }
        return rootView;
    }



    class VoteGroupAdapter extends BaseRecyclerAdapter<BaseHolder> {

        List<ProVoteMyVote> list;

        public VoteGroupAdapter(List<ProVoteMyVote> data) {
            this.list = data;
        }

        @NonNull
        @Override
        public VoteGroupAdapter.VoteGroupViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            return new VoteGroupAdapter.VoteGroupViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.adapter_pro_vote_detail_item_group, viewGroup, false));
        }

        @Override
        public void onBindViewHolder(@NonNull BaseHolder viewHolder, int i) {
            VoteGroupAdapter.VoteGroupViewHolder holder = (VoteGroupAdapter.VoteGroupViewHolder)viewHolder;
            ProVoteMyVote item = list.get(i);
            holder.groupNameText.setText(item.getGroupName());
            holder.groupVoteStatus.setText(item.isVote() ? "已表决" : "待表决");
        }

        @Override
        public int getItemCount() {
            return list == null ? 0 : list.size();
        }

        class VoteGroupViewHolder extends BaseHolder {
            TextView groupNameText;
            TextView groupVoteStatus;
            public VoteGroupViewHolder(@NonNull View itemView) {
                super(itemView);
                groupNameText = itemView.findViewById(R.id.item_group_name);
                groupVoteStatus = itemView.findViewById(R.id.item_group_vote_status);
            }
        }
    }

    private void bindPageData(List<ProVoteMyVote> myVoteList) {
        list.clear();
        list.addAll(myVoteList);
        if(myVoteList == null || myVoteList.size() <= 0) {
            mRecyclerView.setVisibility(View.GONE);
            layoutVoteInfo.setVisibility(View.GONE);
            layoutVoteGoVote.setVisibility(View.GONE);
            layoutVoteEmpty.setVisibility(View.VISIBLE);
        }else if(myVoteList.size() == 1){
            mRecyclerView.setVisibility(View.GONE);
            layoutVoteEmpty.setVisibility(View.GONE);
            ProVoteMyVote myVote = myVoteList.get(0);
            allowChange = myVote.isAllowChange();
            if(myVote.isVote()) {
                layoutVoteInfo.setVisibility(View.VISIBLE);
                layoutVoteGoVote.setVisibility(View.GONE);
                myVoteResult.setText(myVote.getVoteOpinion() == 0 ? "不同意" : "同意");
                myVoteOpinion.setText(TextUtils.isEmpty(myVote.getSupplementOpinion()) ? "无表决意见" : myVote.getSupplementOpinion());
                if(proVote.getStatus() == 2) {
                    if(allowChange) {
                        textAllowChange.setVisibility(View.GONE);
                        btnAllowChange.setVisibility(View.VISIBLE);
                    }else {
                        textAllowChange.setVisibility(View.VISIBLE);
                        btnAllowChange.setVisibility(View.GONE);
                    }
                }else {
                    textAllowChange.setVisibility(View.GONE);
                    btnAllowChange.setVisibility(View.GONE);
                }
                btnAllowChange.setOnClickListener(this);
            }else {
                layoutVoteInfo.setVisibility(View.GONE);
                layoutVoteGoVote.setVisibility(View.VISIBLE);
            }
        }else {
            mRecyclerView.setVisibility(View.VISIBLE);
            layoutVoteInfo.setVisibility(View.GONE);
            layoutVoteGoVote.setVisibility(View.GONE);
            layoutVoteEmpty.setVisibility(View.GONE);
        }
    }

    private void bindPageSingleData(ProVoteMyVote proVoteMyVote) {
        allowChange = proVoteMyVote.isAllowChange();
        if (proVoteMyVote.isVote()) {
            mRecyclerView.setVisibility(View.GONE);
            layoutVoteEmpty.setVisibility(View.GONE);
            layoutVoteInfo.setVisibility(View.VISIBLE);
            layoutVoteGoVote.setVisibility(View.GONE);
            myVoteResult.setText(proVoteMyVote.getVoteOpinion() == 0 ? "不同意" : "同意");
            myVoteOpinion.setText(TextUtils.isEmpty(proVoteMyVote.getSupplementOpinion()) ? "无表决意见" : proVoteMyVote.getSupplementOpinion());
            if(proVote.getStatus() == 2) {
                if(allowChange) {
                    textAllowChange.setVisibility(View.GONE);
                    btnAllowChange.setVisibility(View.VISIBLE);
                }else {
                    textAllowChange.setVisibility(View.VISIBLE);
                    btnAllowChange.setVisibility(View.GONE);
                }
            }else {
                textAllowChange.setVisibility(View.GONE);
                btnAllowChange.setVisibility(View.GONE);
            }
            btnAllowChange.setOnClickListener(this);
        }else {
            mRecyclerView.setVisibility(View.GONE);
            layoutVoteEmpty.setVisibility(View.GONE);
            layoutVoteInfo.setVisibility(View.GONE);
            layoutVoteGoVote.setVisibility(View.VISIBLE);
        }
            /*case 1://未开始
                mRecyclerView.setVisibility(View.GONE);
                layoutVoteEmpty.setVisibility(View.VISIBLE);
                textVoteEmpty.setText("表决还未开始哦，暂时不可表决~");
                layoutVoteInfo.setVisibility(View.GONE);
                layoutVoteGoVote.setVisibility(View.GONE);
                break;
            case 2://已开始
                if(proVote.getVote() != proVote.getTotal()) {
                    mRecyclerView.setVisibility(View.GONE);
                    layoutVoteEmpty.setVisibility(View.GONE);
                    layoutVoteInfo.setVisibility(View.GONE);
                    layoutVoteGoVote.setVisibility(View.VISIBLE);
                }else{
                    mRecyclerView.setVisibility(View.GONE);
                    layoutVoteEmpty.setVisibility(View.GONE);
                    layoutVoteInfo.setVisibility(View.VISIBLE);
                    layoutVoteGoVote.setVisibility(View.GONE);
                }
                break;
            case 3://已结束
                mRecyclerView.setVisibility(View.GONE);
                layoutVoteEmpty.setVisibility(View.GONE);
                layoutVoteInfo.setVisibility(View.VISIBLE);
                layoutVoteGoVote.setVisibility(View.GONE);
                break;
            //case 4://已撤销
            case 5://已通过
                mRecyclerView.setVisibility(View.GONE);
                layoutVoteEmpty.setVisibility(View.VISIBLE);
                textVoteEmpty.setText("表决已通过哦，暂时不可表决~");
                layoutVoteInfo.setVisibility(View.GONE);
                layoutVoteGoVote.setVisibility(View.GONE);
                break;
            case 6://未通过
                mRecyclerView.setVisibility(View.GONE);
                layoutVoteEmpty.setVisibility(View.VISIBLE);
                textVoteEmpty.setText("表决未通过哦，暂时不可表决~");
                layoutVoteInfo.setVisibility(View.GONE);
                layoutVoteGoVote.setVisibility(View.GONE);
                break;*/

    }
    /**
     * 获取详情
     */
    private void fetchMyVote() {
        showLoading();
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        Network.getAPIService()
                .getVoteMyVote_Creditor(userToken, proVote.getId(), proVote.getCreditorId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        hideLoading();
                        mRecyclerView.refreshComplete(1000);
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        LogUtil.e("--response--", json.toString());
                        boolean grouped = json.getAsJsonObject("data").get("grouped").getAsBoolean();
                        try {
                            if(grouped) {
                                JsonArray data = json.getAsJsonObject("data").getAsJsonArray("info");
                                List<ProVoteMyVote> myVoteList = ProVoteMyVote.parse(data);
                                bindPageData(myVoteList);
                            }else {
                                JsonObject data = json.getAsJsonObject("data").getAsJsonObject("info");
                                ProVoteMyVote proVoteMyVote = ProVoteMyVote.parse(data);
                                if(data != null) {
                                    bindPageSingleData(proVoteMyVote);
                                }
                            }
                        }catch (Exception e) {
                            e.printStackTrace();
                        } finally {

                        }
                    }

                    @Override
                    public void onCompleted() {
                        mRecyclerView.refreshComplete(1000);
                        hideLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mRecyclerView.refreshComplete(1000);
                        hideLoading();
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_go_vote:
                Intent intent;
                if(proVote.isGrouped()) {
//                    ProVoteEditVoteNewActivity.start();
                    intent = new Intent(getActivity(), ProVoteMyGroupsActivity.class);
                    intent.putExtra("voteId", proVote.getId());
                    intent.putExtra("creditorId", (proVote.getGroupInfo() != null && proVote.getGroupInfo().size() > 0) ? proVote.getGroupInfo().get(0).getCreditorId() : "");
                    getActivity().startActivityForResult(intent, ProVoteEditVoteActivity.REQUEST_CODE_VOTE);
                }else {
                    intent = new Intent(getActivity(), ProVoteEditVoteActivity.class);
                    intent.putExtra("vote", false);
                    intent.putExtra("voteId", proVote.getId());
                    intent.putExtra("groupId", (proVote.getGroups() != null && proVote.getGroups().size() > 0) ? proVote.getGroups().get(0).getId() : "");
                    getActivity().startActivityForResult(intent, ProVoteEditVoteActivity.REQUEST_CODE_VOTE);
                }
                break;
            case R.id.btn_operate_change:
                intent = new Intent(getActivity(), ProVoteEditVoteActivity.class);
                intent.putExtra("vote", false);
                intent.putExtra("voteId", proVote.getId());
                intent.putExtra("groupId", (proVote.getGroups() != null && proVote.getGroups().size() > 0) ? proVote.getGroups().get(0).getId() : "");
                getActivity().startActivityForResult(intent, ProVoteEditVoteActivity.REQUEST_CODE_VOTE);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }
}
